<template>
  <div class="import">
    <el-card>
      <myexcel
        class="mycard"
        :beforeUpload="beforeUpload"
        :onSuccess="onSuccess"
      ></myexcel>
    </el-card>
  </div>
</template>

<script>
import { addUserBatchApi } from '@/api/employees.js'
export default {
  name: 'import',
  methods: {
    beforeUpload (file) {
      const less = file.size < 2 * 1024 * 1024
      if (!less) {
        this.$message.error('文件大小不得大于2M')
      }
      return less
    },
    async onSuccess ({ header, results }) {
      console.log(results);
      console.log(header);
      const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        手机号: 'mobile',
        工号: 'workNumber',
        转正日期: 'correctionTime'
      }

      const newArr = results.map(item => {
        const newObj = {}
        // Object.keys(obj) 取出所有的键组成数组
        Object.keys(obj).forEach(subitem => {
          // subitem： 入职日期....
          // item是results里面的每一项
          if (subitem === '入职日期' || subitem === '转正日期') {
            newObj[obj[subitem]] = this.turnDate(item[subitem])
          } else {
            newObj[obj[subitem]] = item[subitem]
          }
        })

        return newObj
      })

      console.log(newArr);
      await addUserBatchApi(newArr)
      this.$message.success('批量新增成功')
      this.$router.push('/employees')
    },
    turnDate (days) {
      const mytimer = (days - 1) * 24 * 60 * 60 * 1000
      const mydate = new Date(mytimer)

      mydate.setFullYear(mydate.getFullYear()-70)

      return mydate
    }
  }
}
</script>

<style lang="scss">
.import {
  // margin-top: 200px;
  margin: 20px;

  .mycard {
    margin: 200px 0;
  }
}
</style>
